package com.ea.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.framework.util.Assert;
import com.common.framework.web.response.ResponseJson;
import com.common.framework.web.response.ResultModel;
import com.ea.api.param.LoginParam;
import com.ea.api.vo.UserInfoVO;
import com.ea.repository.entity.SysUser;
import com.ea.service.ISysUserService;
import com.ea.util.RedisUtils;
import com.ea.util.session.SessionUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author XIONG CAI
 * @Date 2024/11/7
 */
@RestController
public class LoginController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private DefaultKaptcha captchaProducer;
    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/login.no")
    @ResponseBody
    public ResultModel login(@RequestBody LoginParam param){
        //UserInfoVO appUserVo = new UserInfoVO();

        String capText = (String) redisUtils.get(param.getUuid());
        if(!param.getCaptcha().equals(capText)){
            return ResultModel.fail(ResponseJson._OTHER_FAIL,"验证码错误");
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_mobile", param.getUsername());
        UserInfoVO userInfoVO = null;
        try {
            userInfoVO = sysUserService.login(param);
        } catch (Exception e) {
            return ResultModel.fail(ResponseJson._OTHER_FAIL, e.getMessage());
        }
        return ResultModel.success(userInfoVO);
    }



    @GetMapping("/captcha.jpg")
    public void generateCaptcha(HttpServletResponse response, HttpSession session, @RequestParam String uuid) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码文本
        String capText = captchaProducer.createText();
        // 将验证码文本存入session
        session.setAttribute("captchaCode", capText);
        redisUtils.set(uuid, capText, 2L, TimeUnit.MINUTES);
        // 生成验证码图片
        BufferedImage bi = captchaProducer.createImage(capText);
        // 输出图片流
        ImageIO.write(bi, "jpg", response.getOutputStream());
    }
}
